package com.heima.search.lintener;

import com.alibaba.fastjson.JSON;
import com.heima.model.search.vos.SearchArticleVo;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SyncArticleListener {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 监听接收消息,保存es索引数据
     * @param msg
     * @throws IOException
     */
    @KafkaListener(topics = "article_es_sync_topic")
    public void onMessage(String msg) throws IOException {
        SearchArticleVo searchArticleVo = JSON.parseObject(msg, SearchArticleVo.class);
        IndexRequest indexRequest = new IndexRequest("app_info_article").id(searchArticleVo.getId().toString());
        indexRequest.source(msg, XContentType.JSON);

        client.index(indexRequest, RequestOptions.DEFAULT);
    }
}
